package com.myflink.day03;

import com.myflink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.collector.selector.OutputSelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.SplitStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;

/**
 * @author Shelly An
 * @create 2020/9/18 9:27
 */
public class Transform_Split {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> fileDS = env.readTextFile("input/sensor-data.log");
        SingleOutputStreamOperator<WaterSensor> sensorDS = fileDS.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] datas = value.split(",");
                //开发中，用包装类多一些。 parse返回的是基本类型
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        });

        //split并不是切成两个流，和keyBy一样，是逻辑上的。split是逻辑上切流
        //低于50正常，50-80警告，80以上报警
        SplitStream<WaterSensor> splitSS = sensorDS.split(new OutputSelector<WaterSensor>() {
            //String 标签  数据的标签，固定的，就是string
            @Override
            public Iterable<String> select(WaterSensor value) {
                if (value.getVc() < 50) {
                    //可以起多个标签
                    return Arrays.asList("normal","happy");
                } else if (value.getVc() < 80) {
                    return Arrays.asList("warn");
                } else {
                    return Arrays.asList("alarm");
                }
            }
        });

        //切分完的流不能直接使用 需要使用.select(流标签)
        splitSS.select("normal").print("myNormal");
        //和上面的结果是一样的
        splitSS.select("happy").print("I'm happy");
        env.execute();
    }
}
